﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace BillingManagment
{
    public partial class SellingSlip : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ToString());
        SqlDataAdapter da;
        DataTable dt;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                ProductCost();
                BindFarmerList();
                txtDate.Text = DateTime.Now.ToShortDateString();
            }
        }

        private void BindData()
        {
            SqlCommand cmd = new SqlCommand("select * from Temp_Items", con);
            da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                GridView1.DataSource = ds;
                GridView1.DataBind();
                int columncount = GridView1.Rows[0].Cells.Count;
                GridView1.Rows[0].Cells.Clear();
                GridView1.Rows[0].Cells.Add(new TableCell());
                GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
                GridView1.Rows[0].Cells[0].Text = "No Records Found";
            }
            else
            {

                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }

        protected void AddNewCustomer(object sender, EventArgs e)
        {
            Label lblProduct = (Label)GridView1.FooterRow.FindControl("lblProduct");
            TextBox txtBucket = (TextBox)GridView1.FooterRow.FindControl("txtBucket");
            TextBox txtRate = (TextBox)GridView1.FooterRow.FindControl("txtRate");
            TextBox txtWait = (TextBox)GridView1.FooterRow.FindControl("txtWait");
            double temp = ((double.Parse(txtRate.Text) * 2.5) / 100) * (double.Parse(txtWait.Text));

            SqlCommand cmd = new SqlCommand("insert into Temp_Items(Product_Name, NoOfBucket,Rate_Per_Forty,Product_Wait,Total_Amount) values ('" + lblProduct.Text + "','" + txtBucket.Text + "','" + txtRate.Text + "','" + txtWait.Text + "','" + temp.ToString() + "')", con);
            da = new SqlDataAdapter(cmd);
            dt = new DataTable();
            da.Fill(dt);
            BindData();
            ProductCost();
            TotalItems();
        }

        protected void EditCustomer(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindData();
        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindData();
        }

        protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
        {
            Label lblProduct = (Label)GridView1.Rows[e.RowIndex].FindControl("lblCustomerID");
            TextBox txtBucket = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBucket");
            TextBox txtRate = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtRate");
            TextBox txtWait = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtWait");
            TextBox txtAmount = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAmount");

            double temp = ((double.Parse(txtRate.Text) * 2.5) / 100) * (double.Parse(txtWait.Text));

            SqlCommand cmd = new SqlCommand("update Temp_Items set Product_Name='" + lblProduct.Text + "',NoOfBucket='" + txtBucket.Text + "',Rate_Per_Forty='" + txtRate.Text + "',Product_Wait='" + txtWait.Text + "',Total_Amount='" + temp.ToString() + "' WHERE S_ID = '" + lblProduct.Text + "'", con);
            da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            GridView1.EditIndex = -1;
            BindData();
            ProductCost();
            TotalItems();
        }

        protected void DeleteCustomer(object sender, EventArgs e)
        {
            LinkButton lnkRemove = (LinkButton)sender;
            GridViewRow gr = (GridViewRow)lnkRemove.NamingContainer;
            Label lblCustomerID = (Label)GridView1.Rows[gr.RowIndex].FindControl("lblCustomerID");

            SqlCommand cmd = new SqlCommand("delete from Temp_Items where S_ID= '" + lblCustomerID.Text + "'", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            BindData();
            ProductCost();
            TotalItems();
        }

        private void ProductCost()
        {
            try
            {
                int temp = 0;
                if (GridView1.Rows.Count > 0)
                    for (int i = 0; i < GridView1.Rows.Count; i++)
                    {
                        Label txtAmount = (Label)GridView1.Rows[i].FindControl("lblAmount");

                        temp += (int.Parse(txtAmount.Text));
                    }
                txtProductCost.Text = temp.ToString();
                if (txtLabourCharge.Text == "")
                    txtLabourCharge.Text = "0";
                else
                    txtTotal.Text = Convert.ToString(Convert.ToInt32(txtProductCost.Text) - Convert.ToInt32(txtLabourCharge.Text));
            }
            catch
            {
            }
        }

        private void TotalItems()
        {
            int temp1 = 0;
            if (GridView1.Rows.Count > 0)
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    Label txtNoOfBucket = (Label)GridView1.Rows[i].FindControl("lblBucket");

                    if (!string.IsNullOrEmpty(txtBucket.Text))
                        temp1 += (int.Parse(txtNoOfBucket.Text));
                }
            hdnTotalBucket.Value = temp1.ToString();
        }

        public void BindFarmerList()
        {
            SqlCommand cmd = new SqlCommand("select ID, (Name +' '+ village) as FName from tbl_Farmer", con);
            DataTable dt = new DataTable();
            SqlDataAdapter oAdp = new SqlDataAdapter(cmd);
            oAdp.Fill(dt);
            ddlFarmerList.DataSource = dt;
            ddlFarmerList.DataValueField = "ID";
            ddlFarmerList.DataTextField = "FName";
            ddlFarmerList.DataBind();
            ddlFarmerList.Items.Insert(0, new ListItem("<----Select---->", "0"));
        }

        protected void ddlFarmerList_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindBucket();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string S_ID = "";
            SqlCommand cmd = new SqlCommand("Insert into tbl_Selling(Farmer_ID,Total_Items,Total_Amount,S_Date) values ('" + ddlFarmerList.SelectedValue + "','" + hdnTotalBucket.Value + "','" + txtTotal.Text + "',Convert(datetime,'" + txtDate.Text + "',103))", con);
            DataTable dt = new DataTable();
            SqlDataAdapter oAdp = new SqlDataAdapter(cmd);
            oAdp.Fill(dt);

            SqlCommand cmd1 = new SqlCommand("select top 1 S_ID from tbl_Selling where Farmer_ID='" + ddlFarmerList.SelectedValue + "' and S_Date=Convert(datetime,'" + txtDate.Text + "',103)", con);
            DataTable dt1 = new DataTable();
            SqlDataAdapter oAdp1 = new SqlDataAdapter(cmd1);
            oAdp1.Fill(dt1);
            if (dt1.Rows.Count > 0)
            {
                S_ID = dt1.Rows[0][0].ToString();
            }

            if (GridView1.Rows.Count > 0)
            {
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    Label ProductName = (Label)GridView1.Rows[i].FindControl("lblProduct");
                    Label Bucket = (Label)GridView1.Rows[i].FindControl("lblBucket");
                    Label Rate = (Label)GridView1.Rows[i].FindControl("lblRate");
                    Label Wait = (Label)GridView1.Rows[i].FindControl("lblWait");
                    Label Amount = (Label)GridView1.Rows[i].FindControl("lblAmount");
                    string temp = Amount.Text;

                    SqlCommand cmd2 = new SqlCommand("Insert into tbl_Selling_Items(S_ID,Farmer_ID,Product_Name, NoOfBucket, Rate_Per_Forty,Product_Wait,Total_Amount) Values ('" + S_ID + "','" + ddlFarmerList.SelectedValue + "', '" + ProductName.Text + "','" + Bucket.Text + "','" + Wait.Text + "','" + Rate.Text + "','" + temp + "')", con);
                    DataTable dt2 = new DataTable();
                    SqlDataAdapter oAdp2 = new SqlDataAdapter(cmd2);
                    oAdp2.Fill(dt2);
                }
            }

            SqlCommand cmd3 = new SqlCommand("Delete from Temp_Items", con);
            DataTable dt3 = new DataTable();
            SqlDataAdapter oAdp3 = new SqlDataAdapter(cmd3);
            oAdp3.Fill(dt3);

            int TBucket = 0;
            int TBucket1 = 0;
            SqlCommand cmd4 = new SqlCommand("Select Total_Bucket from tbl_Inventory_History where Farmer_ID='" + ddlFarmerList.SelectedIndex.ToString() + "' and Modified_Date=Convert(datetime,'" + txtDate.Text + "',103)", con);
            DataTable dt4 = new DataTable();
            SqlDataAdapter oAdp4 = new SqlDataAdapter(cmd4);
            oAdp4.Fill(dt4);
            if (dt4.Rows.Count > 0)
            {
                TBucket1 = Convert.ToInt32(dt4.Rows[0][0].ToString());
                TBucket = TBucket1 - Convert.ToInt32(hdnTotalBucket.Value);
            }

            SqlCommand cmd5 = new SqlCommand("Update tbl_Inventory_History set PreviousBucket='" + Convert.ToString(TBucket) + "', Sold_Bucket='" + hdnTotalBucket.Value + "', Total_Bucket='" + Convert.ToInt32(TBucket) + "'", con);
            DataTable dt5 = new DataTable();
            SqlDataAdapter oAdp5 = new SqlDataAdapter(cmd5);
            oAdp5.Fill(dt5);

            SqlCommand cmd6 = new SqlCommand("Insert into tbl_Current_Ac(Farmer_ID, ModifiedDate, ProductAmount,LabourCharge,PayedAmount,Balance) values ('" + ddlFarmerList.SelectedIndex.ToString() + "',Convert(datetime,'" + txtDate.Text + "',103),'" + txtProductCost.Text + "','" + txtLabourCharge.Text + "','0','" + txtTotal.Text + "')", con);
            DataTable dt6 = new DataTable();
            SqlDataAdapter oAdp6 = new SqlDataAdapter(cmd6);
            oAdp6.Fill(dt6);

            ClearControls();
            Page.RegisterStartupScript("alert", "<script>alert('Data Enter Successfully.');</script>");
            Response.Redirect("SellingSlip.aspx");
        }

        public void BindBucket()
        {
            SqlCommand cmd = new SqlCommand("select NoOfBucket from tbl_Inward where Farmer_ID='" + ddlFarmerList.SelectedValue + "' and Date=Convert(datetime,'" + txtDate.Text + "',103)", con);
            DataTable dt = new DataTable();
            SqlDataAdapter oAdp = new SqlDataAdapter(cmd);
            oAdp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                txtBucket.Text = dt.Rows[0][0].ToString();
                txtLabourCharge.Text = Convert.ToString(Convert.ToInt32(txtBucket.Text) * .90);
            }
        }

        public void ClearControls()
        {
            txtBucket.Text = "";
            txtDate.Text = "";
            txtLabourCharge.Text = "";
            txtProductCost.Text = "";
            txtTotal.Text = "";
            GridView1.DataSource = null;
            GridView1.DataBind();
        }

        protected void txtDate_TextChanged(object sender, EventArgs e)
        {
            BindBucket();
        }
    }
}